package com.learn.acm.netty.protobuf1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * 服务端
 *
 */
@Slf4j
public class NettyServer {

    public static void main(String[] args) {
        /**
         * 创建bossGroup和workerGroup
         * 说明
         *  1.创建两个线程组 bossGroup和workerGroup
         *  2.bossGroup只是处理连接请求， workerGroup处理客户端业务
         *  3.两个都是无限循环
         */
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 创建服务端启动对象，配置参数
            ServerBootstrap bootstrap = new ServerBootstrap();

            // 使用链式编程来设置
            bootstrap.group(bossGroup, workerGroup) // 设置两个线程组
                    .channel(NioServerSocketChannel.class) // 设置NioServerSocketChannel 作为服务器的通道实现
                    .option(ChannelOption.SO_BACKLOG, 128) // 设置线程队列得到连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true) // 设置保持活动连接状态
                    .childHandler(new ChannelInitializer<SocketChannel>() { // 创建一个通道测试对象（匿名对象）
                        /**
                         * 给pipeline设置处理器
                         * @param socketChannel
                         * @throws Exception
                         */
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("encode", new ProtobufEncoder());
                            pipeline.addLast("decode", new ProtobufDecoder(DataOuterClass.Data.newBuilder().build()));
                            pipeline.addLast(new NettyServerHandler());
                        }
                    }); // 给我们的workerGroup的 eventLoop对应的管道设置处理器
            log.info("服务器 ready....");
            // 绑定一个端口并且同步， 生成了一个 ChannelFuture 对象
            ChannelFuture channelFuture = bootstrap.bind(8999).sync();
            // 对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
